package com.vchello.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 
 * @author power
 *
 *         2016年4月26日
 */
public class SerializeUtil {

	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {

		}
		return null;
	}

	// public static Object unserialize(byte[] bytes) {
	// ByteArrayInputStream bais = null;
	// try {
	// // 反序列化
	// bais = new ByteArrayInputStream(bytes);
	// ObjectInputStream ois = new ObjectInputStream(bais);
	// return ois.readObject();
	// } catch (Exception e) {
	//
	// }
	// return null;
	// }

	// 反序列化
	public static Object unserialize(byte[] byt) {
		ObjectInputStream oii = null;
		ByteArrayInputStream bis = null;
		bis = new ByteArrayInputStream(byt);
		try {
			oii = new ObjectInputStream(bis);
			Object obj = oii.readObject();
			return obj;
		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;
	}

	public byte[] getByte(Object object) {
		byte[] bt = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		try {
			if (object != null) {
				ObjectOutputStream objos = new ObjectOutputStream(baos);
				objos.writeObject(object);
				bt = baos.toByteArray();
			}
		} catch (Exception e) {
			bt = (byte[]) null;
			e.printStackTrace();

		}
		return bt;
	}
}
